package com.shkco.basic.interceptor;

import com.shkco.basic.jwt.*;
import com.shkco.system.annotation.PreAuthorize;
import com.shkco.system.mapper.PermissionMapper;
import com.shkco.user.domain.Logininfo;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PublicKey;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");

        if (token != null){

            Logininfo logininfo = null;
            try {
                // 获取公钥
                PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("auth_rsa.pub").getFile());
                // 解密
                Payload<LoginData> payload = JwtUtils.getInfoFromToken(token, publicKey, LoginData.class);
                // 获取登录信息
                logininfo = payload.getLoginData().getLogininfo();
            } catch (ExpiredJwtException e) {
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().println("{\"success\":false,\"msg\":\"timeout\"}");
                return false;
            }

            // 刷新过期时间
//                redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
            // 前台用户直接放行
            if (logininfo.getType() == 1){
                return true;
            }
            // 获取当前访问接口的自定义注解的sn
            HandlerMethod handlerMethod = (HandlerMethod)handler;
            PreAuthorize preAuthorize = handlerMethod.getMethodAnnotation(PreAuthorize.class);
            // 接口没有这个注解直接放行
            if (preAuthorize == null){
                return true;
            } else {
                // 如果有这个注解，直接获取这个注解的sn属性值
                String sn = preAuthorize.sn();
                // 获取当前登录人的所有权限的sn
                List<String> myPermission = permissionMapper.getPermissionsByLogininfoId(logininfo.getId());
                if (myPermission.contains(sn)) {
                    return true;
                } else {
                    response.setContentType("application/json;charset=UTF-8");
                    response.getWriter().println("{\"success\":false,\"msg\":\"noPermission\"}");
                    return false;
                }
            }
        }
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println("{\"success\":false,\"msg\":\"noLogin\"}");
        return false;
    }
}
